//========================================================================
//Copyright 2007-2010 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at 
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================

package com.dyuproject.kvstore;

import java.io.IOException;
import java.net.URL;
import java.util.Properties;

/**
 * Configuration for the store via java properties.
 * Implementation details and configuration of the store are configured 
 * in the properties file.  This removes hard-coded dependency on particular stores.
 *
 * @author David Yu
 * @created Jan 29, 2010
 */
public final class StoreEnvironment
{
    
    static final String CONFIG_LOCATION = "kvstore.properties";
    
    private static StoreEnvironment __instance;
    
    /**
     * Gets the single environment instance.
     */
    public static StoreEnvironment getInstance()
    {
        StoreEnvironment instance = __instance;
        if(instance == null)
        {
            synchronized(StoreEnvironment.class)
            {
                instance = __instance;
                if(instance == null)
                    instance = __instance = new StoreEnvironment(CONFIG_LOCATION);
            }
        }
        return instance;
    }
    
    static URL getResource(String resourceLoc)
    {
        URL resource = Thread.currentThread().getContextClassLoader().getResource(resourceLoc);
        return resource == null ? StoreEnvironment.class.getClassLoader().getResource(resourceLoc) : 
            resource;
    }
    
    static Class<?> loadClass(String className)
    {
        Class<?> clazz;
        try
        {
            clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        }
        catch (ClassNotFoundException e)
        {
            try
            {
                clazz = StoreEnvironment.class.getClassLoader().loadClass(className);
            }
            catch (ClassNotFoundException e1)
            {
                throw new RuntimeException(e1);
            }
        }
        return clazz;
    }
    
    @SuppressWarnings("unchecked")
    static <T> T newInstance(String className)
    {
        Class<?> clazz = loadClass(className);
        try
        {
            return (T)clazz.newInstance();
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }
    
    static StoreManager loadManager(Properties props)
    {
        String managerParam = props.getProperty("store.manager");
        if(managerParam==null)
            throw new IllegalStateException("store.manager not found");
        
        return (StoreManager)newInstance(managerParam);
    }
    
    final Properties props;
    final StoreManager manager;
    
    public StoreEnvironment(String resourceLoc)
    {
        URL resource = getResource(resourceLoc);
        if(resource==null)
            throw new IllegalStateException("resource: " + resourceLoc + " not found");
        
        Properties props = new Properties();
        try
        {
            props.load(resource.openStream());
        }
        catch(IOException e)
        {
            throw new RuntimeException(e);
        }
        
        this.props = props;
        manager = loadManager(props);
        manager.init(props);
    }
    
    public StoreEnvironment(Properties props)
    {
        this.props = props;
        manager = loadManager(props);
        manager.init(props);
    }
    
    /**
     * Gets or creates the store if it isn't loaded yet.
     */
    public <T> Store<T> getStore(String name, Serializer<T> serializer)
    {
        return manager.getStore(name, serializer);
    }
    
    public void close()
    {
        manager.close();
    }
    

}
